package com.liaoban.app.ui.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.liaoban.app.R;
import com.liaoban.app.api.type.User;
import com.liaoban.app.api.type.event.LocationEvent;
import com.liaoban.app.api.type.event.LoginEvent;
import com.liaoban.app.api.type.request.LoginRequest;
import com.liaoban.app.biz.CommonBiz;
import com.liaoban.app.helper.ToastHelper;
import com.liaoban.app.ui.base.BaseToolbarActivity;
import com.liaoban.app.util.CommonUtils;
import com.liaoban.app.util.VerifyUtil;
import com.liaoban.app.widget.ClearEditText;
import com.liaoban.app.widget.MyTextWatcher;
import com.netease.nim.demo.DemoCache;
import com.netease.nim.demo.config.preference.Preferences;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nimlib.sdk.AbortableFuture;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.LoginInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ybc on 2018/7/6 0006.
 * 手机登录
 */
public class PhoneLoginActivity extends BaseToolbarActivity {

    @BindView(R.id.et_phone)
    ClearEditText etPhone;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.iv_see)
    ImageView ivSee;
    @BindView(R.id.tv_login)
    TextView tvLogin;

    private AbortableFuture<LoginInfo> loginRequestNim;
    private String longitude = "0"; //经度
    private String latitude = "0"; // 纬度

    @Override
    protected String getNewTitle() {
        return getString(R.string.app_name);
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_phone_login;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setNeedOnBus(true);
        initListener();
    }

    private void initListener() {
        MyTextWatcher myTextWatcher = new MyTextWatcher(() -> {
            if (VerifyUtil.isMobileNO(etPhone.getText().toString().trim()) &&
                    etPwd.getText().toString().trim().length() >= 6) {
                tvLogin.setEnabled(true);
                tvLogin.setBackgroundResource(R.drawable.shape_yellow);
            } else {
                tvLogin.setEnabled(false);
                tvLogin.setBackgroundResource(R.drawable.shape_line);
            }
        });
        etPhone.addTextChangedListener(myTextWatcher);
        etPwd.addTextChangedListener(myTextWatcher);
    }

    @OnClick(R.id.iv_see)
    public void see() {
        if (ivSee.isSelected()) {
            // 显示为密码
            etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            // 使光标始终在最后位置
            Editable editable = etPwd.getText();
            Selection.setSelection(editable, editable.length());
            ivSee.setSelected(false);
        } else {
            // 显示为普通文本
            etPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            // 使光标始终在最后位置
            Editable editable = etPwd.getText();
            Selection.setSelection(editable, editable.length());
            ivSee.setSelected(true);
        }
    }

    @OnClick(R.id.tv_login)
    public void login() {
        String userTel = etPhone.getText().toString().trim();
        String pwd = etPwd.getText().toString().trim();
        showRunningDialog();
        LoginRequest loginRequest = new LoginRequest();
        loginRequest.setUserTel(userTel);
        loginRequest.setPassword(pwd);
        loginRequest.setLongitude(longitude);
        loginRequest.setLatitude(latitude);
        loginRequest.setJpush_id(CommonUtils.getRegistrationID(this));
        startTask(CommonBiz.getInstance().login(loginRequest), userBaseResponse -> {
            if (userBaseResponse.code != 1) {
                ToastHelper.show(PhoneLoginActivity.this, userBaseResponse.msg);
                return;
            }
            // 云信登录
            final String account = userBaseResponse.data.getWuserTel();
            final String token = userBaseResponse.data.getYunToken();
            loginRequestNim = NimUIKit.login(new LoginInfo(account, token), new RequestCallback<LoginInfo>() {
                @Override
                public void onSuccess(LoginInfo param) {
                    onLoginDone();

                    DemoCache.setAccount(account);
                    saveLoginInfo(account, token);

                    // 初始化消息提醒配置
                    //initNotificationConfig();

                    ToastHelper.show(PhoneLoginActivity.this, "登录成功");
                    User user = userBaseResponse.data;
                    CommonUtils.saveUser(PhoneLoginActivity.this, user);
                    EventBus.getDefault().post(new LoginEvent());
                    finish();
                }

                @Override
                public void onFailed(int code) {
                    onLoginDone();
                    if (code == 302 || code == 404) {
                        ToastHelper.show(PhoneLoginActivity.this, com.netease.nim.demo.R.string.login_failed);
                    } else {
                        ToastHelper.show(PhoneLoginActivity.this, "登录失败: " + code);
                    }
                }

                @Override
                public void onException(Throwable exception) {
                    ToastHelper.show(PhoneLoginActivity.this, com.netease.nim.demo.R.string.login_exception);
                    onLoginDone();
                }
            });

        });
    }

    private void saveLoginInfo(final String account, final String token) {
        Preferences.saveUserAccount(account);
        Preferences.saveUserToken(token);
    }

    private void onLoginDone() {
        loginRequestNim = null;
    }

    @OnClick(R.id.tv_forget_pwd)
    public void forgetPwd() {
        startActivity(new Intent(this, ForgetPwdActivity.class));
    }

    @OnClick(R.id.tv_register)
    public void register() {
        startActivity(new Intent(this, RegisterActivity.class));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLocationEvent(LocationEvent locationEvent) {
        longitude = String.valueOf(locationEvent.longitude);
        latitude = String.valueOf(locationEvent.latitude);
    }

}
